<?php
namespace app\user\controller;

use think\Config;
use think\Controller;
use think\Request;
use think\Session;
use think\Db;

class Open extends Controller
{
    public function _empty(){
    }

    public function password(){
        if ($this->request->isPost()){
            $password = \request()->post('password','');
            if ($password == ''){
                return ['status'=>0,'message'=>'口令不能为空'];
            }
            $command = "25d55ad283aa400af464c76d713c07ad";
            if (md5($password) != $command){
                return ['status'=>0,'message'=>'口令错误'];
            }
            Session::set('has_key',1);
            return ['status'=>1,'message'=>'口令成功','url'=>url('login')];
        }
        return $this->fetch('password');
    }
    /**
     * 系统登录
     */
    public function Login(){
        //Post请求操作
        if(IsPost()){
            $Data = Param();
//            dump($Data);die;
            $Where['username|email'] = $Data['username'];
            $Where['password_login'] = md5($Data['password']);
            // $Where['password_pay'] = md5($Data['password_zs']);
            $UserInfo = Db::name('user')->where($Where)->find();
            if(empty($UserInfo)){
                return ['status'=>0,'message'=>'用户名或密码错误'];
            }
            //验证码
//            if (!CheckVerify($Data['code'])){
//                return ['status'=>2,'message'=>'验证码错误'];
//            }
            Session::set('user_id',$UserInfo['id']);
            Session::set('init_flag',1);
            UserLog($UserInfo['id'],$UserInfo['username']);
            return ['status'=>1,'message'=>'登陆成功','url'=>url("Index/Index")];
        }
        //判断用户是否已经登录
        $user_id = Session::get('user_id');
        if(empty($user_id)){
            $lang_type = Config::get('lang_type');
            $lang_arr = Config::get('lang_list');
            $index = array_search(cookie('think_var'),$lang_arr);
            unset($lang_arr[$index]);
            $this->assign('lang_type',$lang_type);
            $this->assign('lang_arr',$lang_arr);
            $hasKey = Session::get('has_key');
            $href = '';
            if (!$hasKey || $hasKey != 1){
//                $href = url('Open/password');
                $this->redirect('Open/password');
                return false;
            }
            return $this->fetch('Login',compact('href'));
        }else{
            $this->redirect('Index/index');
        }
    }

    public function Verify(){
        return Verify();
    }

    public function Register(){
        if (IsPost()){
            $Data = Param();
            if ($Data['username'] == ''){
                return ['status'=>0,'message'=>'请输入账号'];
            }
            if (!preg_match('/^(?!\d+$)(?![A-Za-z]+$)[a-zA-Z0-9]{2,}$/i',$Data['username'])){
                return ['status' => 0, 'message' => '账号必须为字母+数字'];
            }
            $check_username = UserInfo(['username'=>$Data['username']]);
            if ($check_username){
                return ['status' => 0, 'message' => '账号已存在'];
            }
//            if ($Data['name'] == ''){
//                return ['status' => 0, 'message' => '请输入昵称'];
//            }
//            if (!preg_match('/^[^\s]*$/',$Data['name'])){
//                return ['status' => 0, 'message' => '昵称不能有空格'];
//            }
//            $check_name = UserInfo(['name'=>$Data['name']]);
//            if ($check_name){
//                return ['status' => 0, 'message' => '昵称已存在'];
//            }
//            if ($Data['phone'] == ''){
//                return ['status' => 0, 'message' => '手机号不能为空'];
//            }
//            $check_phone = UserInfo(['phone'=>$Data['phone']]);
//            if ($check_phone){
//                return ['status' => 0, 'message' => '手机号已存在'];
//            }
            if ($Data['email'] == ''){
                return ['status' => 0, 'message' => '邮箱不能为空'];
            }
            if (!preg_match('/^\w+@[a-zA-Z0-9]+((\.[a-z0-9A-Z]{1,})+)$/',$Data['email'])){
                return ['status' => 0, 'message' => '邮箱格式错误'];
            }
            $check_phone = UserInfo(['email'=>$Data['email']]);
            if ($check_phone){
                return ['status' => 0, 'message' => '邮箱已存在'];
            }
            //验证码
            $Config = \Config();
            if ($Config['code_toggle'] == 1){
                $res = checkCode($Data['email'],$Data['code'],2);
                if ($res['status'] != 1){
                    return ['status' => 0, 'message' => $res['message']];
                }
            }

            if (strlen($Data['pass_login']) < 6){
                return ['status' => 0, 'message' => '登录密码至少6位'];
            }
            $recommend = UserInfo(['recommend_num'=>$Data['recommend']]);
            if (!$recommend){
                return ['status' => 0, 'message' => '邀请码不存在'];
            }
            $NumArr = Db::name('user')->column('recommend_num');
            do{
                $recommend_num = randString();
            }while(in_array($recommend_num,$NumArr));
            $AddData = [
                'username' => $Data['username'],   //账号
//                'name' => $Data['name'],   //账号
//                'phone' => $Data['phone'],   //账号
                'email' => $Data['email'],   //邮箱
                'password_login' => md5($Data['pass_login']),  //登录密码
//                'password_pay' => md5($Data['pass_pay']),  //支付密码
                'password_pay' => md5(123456),  //支付密码
                'status' => 1,    //账号状态 0未激活 1已激活 -1冻结
                'recommend'=>$recommend['id'],    //推荐人ID
                'recommend_num'=>$recommend_num,    //邀请码
                'add_time'=>time(),    //注册时间
            ];
            if ($user_id = Db::name('user')->insertGetId($AddData)){
                Db::query('call add_user_recommend(:id,:recommend_id)',['id'=>$user_id,'recommend_id'=>$recommend['id']]);    //创建推荐关系
                Db::query('call user_uplevel(:user_id)',['user_id'=>$user_id]); //升级（推荐 团队 人数u）
                //检查上级推荐人数 发放网图待发放奖励
                CheckRecommendCount($recommend['id']);
                Session::set('user_id',$user_id);
                return ['status' => 1, 'message' => '注册成功','url'=>url('Index/Index')];
            }else{
                return ['status' => 0, 'message' => '注册失败'];
            }
            dump($Data);die;
        }

//        dump(cookie('think_var'));die;
        $recommend = Param('recommend');
        $this->assign('recommend',$recommend);
        $lang_type = Config::get('lang_type');
        $lang_arr = Config::get('lang_list');
        $index = array_search(cookie('think_var'),$lang_arr);
        unset($lang_arr[$index]);
        $this->assign('lang_type',$lang_type);
        $this->assign('lang_arr',$lang_arr);
        return $this->fetch('Register');
    }

    public function CheckUser(){
        if (IsPost()){
            $recommend_code = Param('recommend');
            if ($recommend_code == ''){
                return ReturnMsg(0,'请输入邀请码');
            }
            $RecommendInfo = UserInfo(['recommend_num'=>$recommend_code]);
            if (!$RecommendInfo){
                return ReturnMsg(0,'组织不存在');
            }
//            return ReturnMsg(1,$RecommendInfo['username']);
            return ReturnMsg(1,'验证成功');
        }
    }

    public function ChangeLang(){
        $lang = Param('lang');
        switch ($lang){
            case 'zh-cn':
                cookie('think_var','zh-cn');
                break;
            case 'zh-tw':
                cookie('think_var','zh-tw');
                break;
            case 'en-us':
                cookie('think_var','en-us');
                break;
            case 'vn-vie':
                cookie('think_var','vn-vie');
                break;

        }
        return true;
    }

    public function FindPass(){
        //系统参数
        $Config = Config();
        $this->assign('title',$Config['web_name']);

        //Post请求
        if(IsPost()){
            //请求数据
            $Data = Param();

//            //判断账号手机号是否匹配
//            if($Data['RegType'] == 1){  //手机号验证
//                $UserInfo = UserInfo(['username'=>$Data['username'],'phone'=>$Data['phone']]);
//                $Message = "账号与手机号不匹配";
//            }else{  //邮箱验证
//                $UserInfo = UserInfo(['username'=>$Data['username'],'email'=>$Data['email']]);
//                $Message = "账号与邮箱不匹配";
//            }
//            if(empty($UserInfo)){
//                return ['status'=>0,'message'=>$Message];
//            }

            $UserInfo = UserInfo(['email'=>$Data['email']]);
            if (!$UserInfo){
                return ['status'=>0,'message'=>'邮箱未注册过'];
            }

            //验证码验证
//            if($Data['RegType'] == 1){  //手机验证码
//                $Phone = $Data['mobile_prefix'].$Data['phone'];
//                $CodeRes = checkCode($Phone,$Data['code'],1);
//            }else{
//                $CodeRes = checkCode($Data['email'],$Data['code'],2);
//            }
            if ($Config['code_toggle'] == 1){
                $CodeRes = checkCode($Data['email'],$Data['code'],2);
                if($CodeRes['status'] != 1){
                    return $CodeRes;
                }
            }

//            $Secret = Db::name('user_secret')->where(['user_id'=>$UserInfo['id']])->find();
//            if ($Data['answer'] != $Secret['answer']){
//                return ['status'=>0,'message'=>'密保问题回答错误'];
//            }
            if ($Data['pass_login'] == ''){
                return ['status'=>0,'message'=>'请输入新密码'];
            }
            if (strlen($Data['pass_login']) < 6){
                return ['status'=>0,'message'=>'密码至少6位'];
            }
            //更新密码
            $Save['password_login'] = md5($Data['pass_login']);
            if(Db::name('user')->where(['id'=>$UserInfo['id']])->update($Save)){
                return ['status'=>1,'message'=>'密码修改成功'];
            }else{
                return ['status'=>0,'message'=>'新密码与原密码一致'];
            }
        }
        return $this->fetch('FindPass');
    }

    public function SendEmail(){
        $Data = Param();
        if ($Data['email'] == ''){
            return ['status' => 0, 'message' => '请输入邮箱'];
        }
        if (!preg_match('/^\w+@[a-zA-Z0-9]+((\.[a-z0-9A-Z]{1,})+)$/',$Data['email'])){
            return ['status' => 0, 'message' => '邮箱格式错误'];
        }
        $code = randNumber();
        $res = SendEmailOutlook($Data['email'],$code);
        if ($res){
            AddCode($Data['email'],$code,2);
            return ['status' => 1, 'message' => '发送成功'];
        }else{
            return ['status' => 0, 'message' => $res];

        }
    }
    /**
     * 退出登录
     */
    public function LoginOut(){
        //注销Session信息
        Session::delete('user_id');

        //跳转登录界面
        $this->redirect('Open/Login');
    }

    public function https_request($url, $data = null)
    {
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
        if (!empty($data)) {
            curl_setopt($curl, CURLOPT_POST, 1);
            curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
        }
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $output = curl_exec($curl);
        curl_close($curl);
        return $output;
    }
}